package com.szalay.desktopsearch.search;

import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingUtilities;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;

/**
 * Search class.
 * @author szalay
 */
public class Search {
    private final List<SearchListener> listeners = new ArrayList<SearchListener>();

    /** Solr. */
    private final SolrServer solr;

    /** Create a new search. */
    public Search(final SolrServer solr) {
        this.solr = solr;
    }

    /**
     *  Searches for the specific term.
     * @param term 
     */
    public QueryResponse search(final String term, final int start, final int pageSize) throws SolrServerException {
        final SolrQuery query = new SolrQuery();
        query.setQuery(term);
        query.setFields("*,score");
        query.setHighlight(true);
        query.setIncludeScore(true);
        query.setRows(pageSize);
        query.setStart(start);

        for (final SearchListener l : listeners) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    l.searchStarting(term);
                }
            });
        }

        final QueryResponse queryResult = solr.query(query);
        for (final SearchListener l : listeners) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    l.searchFinished(queryResult);
                }
            });
        }
        return queryResult;
    }
    
    /**
     * Adds a new search listener.
     * @param l 
     */
    public void addSearchListener(final SearchListener l) {
        listeners.add(l);
    }
    
    /**
     *  Removes a search listener.
     * @param l 
     */
    public void removeSearchListener(final SearchListener l) {
        listeners.remove(l);
    }
}
